<?php
/**
 * @version $Id: controller.php,v 1.3 2009/06/04 20:13:37 dgravato Exp $
 * @package    sketchup
 * @subpackage
 * @author     Chris Borkowski {@link http://www.guggenheim.org}
 * @author     Created on 06-May-2009
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.controller' );

class SketchupController extends JController
{
	function __construct( $default = array() )
	{
		parent::__construct( $default );
		$this->registerTask( 'add' , 'edit' );
		$this->registerTask( 'apply', 'save' );
		$this->registerTask( 'unpublish', 'publish' );
		$this->registerTask( 'jury', 'jury' );
		$this->registerTask( 'finalist', 'finalist' );
	
	}

	function edit()
	{
		global $option;

		$row =& JTable::getInstance('sketchup', 'Table');
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		$id = $cid[0];
		$row->load($id);
		$lists = array();
		$lists['jury_select'] = JHTML::_('select.booleanlist', 'jury_select', 'class="inputbox"', $row->jury_select);
		$lists['finalist'] = JHTML::_('select.booleanlist', 'finalist', 'class="inputbox"', $row->finalist);
		$lists['published'] = JHTML::_('select.booleanlist', 'published', 'class="inputbox"', $row->published);

		HTML_sketchups::editSketchup($row, $lists, $option);
	}

	function save()
	{
		global $option;

		JRequest::checkToken() or die( 'Invalid Token' );

		$row =& JTable::getInstance('sketchup', 'Table');

		if (!$row->bind(JRequest::get('post'))) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}

		//for the description editor
		$row->p_description = JRequest::getVar( 'p_description', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$row->id = (int) $row->id;
		$row->finalist = (int) $row->finalist;
		$row->jury_select = (int) $row->jury_select;

		$date =& JFactory::getDate($row->sub_date);
		$row->sub_date = $date->toMySQL();

		if (!$row->store()) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}

		switch ($this->_task)
		{
			case 'apply':
				$msg = 'Changes to Sketchup saved';
				$link = 'index.php?option=' . $option . '&task=edit&cid[]='. $row->id;
				break;
					
			case 'save':
			default:
				$msg = 'Sketchup Saved';
				$link = 'index.php?option=' . $option;
				break;
		}
			
		$this->setRedirect($link, $msg);
	}

	function showSketchups()
	{
		global $option, $mainframe;

		$limit = JRequest::getVar('limit', $mainframe->getCfg('list_limit'));
		$limitstart = JRequest::getVar('limitstart', 0);

		$db =& JFactory::getDBO();
		$query = "SELECT count(*) FROM #__sketchup";
		$db->setQuery( $query );
		$total = $db->loadResult();

		$query = "SELECT * FROM #__sketchup";
		$db->setQuery( $query, $limitstart, $limit );
		$rows = $db->loadObjectList();

		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}

		jimport('joomla.html.pagination');

		$pageNav = new JPagination($total, $limitstart, $limit);

		HTML_sketchups::showSketchups( $option, $rows, $pageNav );
	}

	function remove()
	{
		global $option;
		$cid = JRequest::getVar( 'cid', array(), '', 'array' );
		$db =& JFactory::getDBO();
			
		if(count($cid))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			$query = "DELETE FROM #__sketchup WHERE id IN ( $cids )";
			$db->setQuery( $query );
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window. history.go(-1); </script>\n";
			}
		}

		$this->setRedirect( 'index.php?option=' . $option );
	}

	function publish()
	{
		global $option;

		$cid = JRequest::getVar( 'cid', array(), '', 'array' );

		if( $this->_task == 'publish')
		{
			$publish = 1;
		}
		else
		{
			$publish = 0;
		}

		$SketchupTable =& JTable::getInstance('sketchup', 'Table');
		$SketchupTable->publish($cid, $publish);
		$this->setRedirect( 'index.php?option=' . $option );
	}

	/* method to manage jury selections
	 * @ access public
	 * mixed vars
	 */
	
	function jury()
	{
		global $option;

		$cid = JRequest::getVar( 'cid', array(), '', 'array' );
		$jury_state = JRequest::getVar( 'jury_state', 'int' );
		
		$db =& JFactory::getDBO();
		
		if ($jury_state == 0)
		{
			$num= 1;
		} else {
			$num= 0;
		}
			
		if(count($cid))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			$query = "UPDATE #__sketchup SET jury_select = $num WHERE id = ( $cids )";
			$db->setQuery( $query );
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window. history.go(-1); </script>\n";
			}
		}

		$this->setRedirect( 'index.php?option=' . $option );
	}
	
	
	/* method to manage finalist selections
	 * @ access public
	 * mixed vars
	 */
	
	function finalist()
	{
		global $option;

		$cid = JRequest::getVar( 'cid', array(), '', 'array' );
		$finalist_state = JRequest::getVar( 'finalist_state', 'int' );
		
		$db =& JFactory::getDBO();
		
		if ($finalist_state == 0)
		{
			$num= 1;
		} else {
			$num= 0;
		}
			
		if(count($cid))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			$query = "UPDATE #__sketchup SET finalist = $num WHERE id = ( $cids )";
			$db->setQuery( $query );
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window. history.go(-1); </script>\n";
			}
		}

		$this->setRedirect( 'index.php?option=' . $option );
	}




	function comments()
	{
		global $option, $mainframe;

		$limit = JRequest::getVar('limit', $mainframe->getCfg('list_limit'));
		$limitstart = JRequest::getVar('limitstart', 0);

		$db =& JFactory::getDBO();
		$query = "SELECT count(*) FROM #__sketchup_comments";
		$db->setQuery( $query );
		$total = $db->loadResult();

		$query = "SELECT c.*, r.p_title FROM #__sketchup_comments AS c LEFT JOIN #__sketchup AS r ON r.id = c.sketchup_id ";
		$db->setQuery( $query, $limitstart, $limit );
		$rows = $db->loadObjectList();

		if ($db->getErrorNum())
		{
			echo $db->stderr();
			return false;
		}

		jimport('joomla.html.pagination');
		$pageNav = new JPagination($total, $limitstart, $limit);
		HTML_sketchups::showComments( $option, $rows, $pageNav );
	}

	function editComment()
	{
		global $option;

		$row =& JTable::getInstance('comment', 'Table');
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		$id = $cid[0];
		$row->load($id);
		HTML_sketchups::editComment($row, $option);
	}

	function saveComment()
	{
		global $option;

		$row =& JTable::getInstance('comment', 'Table');
		$row->comment_text = JRequest::getVar( 'comment_text', '', 'post', 'string', JREQUEST_ALLOWRAW );

		if (!$row->bind(JRequest::get('post'))) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}

		if (!$row->store()) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}

		$this->setRedirect('index.php?option=' . $option . '&task=comments', 'Comment changes saved');
	}

	function removeComment()
	{
		global $option;
		$cid = JRequest::getVar( 'cid', array(), '', 'array' );
		$db =& JFactory::getDBO();

		if(count($cid))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			$query = "DELETE FROM #__sketchup_comments WHERE id IN ( $cids )";
			$db->setQuery( $query );
				
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window.history.go(-1); </script>\n";
			}
		}

		$this->setRedirect( 'index.php?option=' . $option . '&task=comments' );
	}

	
	





	
	/* method to manage thumbnails
	 * @ access public
	 * mixed vars
	 */

	function thumbs()
	{
		global $option, $mainframe;

		$limit = JRequest::getVar('limit', $mainframe->getCfg('list_limit'));
		$limitstart = JRequest::getVar('limitstart', 0);

		$db =& JFactory::getDBO();
		$query = "SELECT count(*) FROM #__sketchup";
		$db->setQuery( $query );
		$total = $db->loadResult();
		//make more granular to check all rows
		$query = "SELECT * FROM #__sketchup";
		$db->setQuery( $query, $limitstart, $limit );
		$rows = $db->loadObjectList();

		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}

		jimport('joomla.html.pagination');

		$pageNav = new JPagination($total, $limitstart, $limit);

		HTML_sketchups::showSketchupsThumbs( $option, $rows, $pageNav );
	}

	/*find which projects don't have thumbs
		* returns array for file names
		* @ access private
		*/

	function _findThumbs(){

		$db =& JFactory::getDBO();
		$query = "SELECT image1, thumb1 FROM #__sketchup WHERE thumb1=''";
		$db->setQuery( $query, 0, 0);
		$rows = $db->loadObjectList();

		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}

		//lets just get the file name from the db query
		// this path needs to go global

		$find_path = array("/var/www/www.guggenheim.org/docs/images/content/sketchup/uploads/");
		$replace_path = array("");
		//this was a test
		//$arr = array("/www/path/file1.jpg","/www/path/file2.jpg","/www/path/file3.jpg");
		$full_images = array();
		$full_images = str_replace($find_path,$replace_path,$rows);

		return $full_images;
	}

	/* method for making thumbnails
	 * this is jenky
	 * @ var mixed
	 * access public
		*/

	function makethumbs()
	{

		global $option, $mainframe;

		//First we'll access to the file system and we'll use the Joomla way to all safe.
		jimport('joomla.filesystem.file');
		$uploads_path = JPATH_ROOT . DS . "images". DS ."content" . DS ."sketchup". DS . "uploads" ;
		$thumb_path = JPATH_ROOT . DS . "images". DS ."content" . DS ."sketchup". DS . "thumbs" ;

		// this is the width in px that we're telling GD to scale to, where's imagemagik whe you need it.
		$new_w = 90;
		// where our source images live b/c GD needs to read them
		$cfg_fullsizepics_path = $uploads_path;
		//where we're sending them when we are done
		$cfg_thumb_path = $thumb_path;
		// we need one more path for this to work
		$filepath = $uploads_path ;
		// the directory
		$dir = dir($filepath);

		//check folders
			
		while($entry=$dir->read()) {
			//check the files
			if($entry == "." || $entry == "..") {

				continue;
			}
				
			$fp = @fopen("$filepath/$entry","r");

			$photo_filename = "$entry";

			$image_stats = GetImageSize($cfg_fullsizepics_path."/".$entry);

			$imagewidth = $image_stats[0];

			$imageheight = $image_stats[1];

			$img_type = $image_stats[2];

			$ratio = ($imagewidth / $new_w);

			$new_h = round($imageheight / $ratio);

			if (!file_exists($cfg_thumb_path."/".$entry))  {

				if ($img_type=="2") {

					$src_img = imagecreatefromjpeg($cfg_fullsizepics_path."/".$entry);

					$dst_img = imagecreatetruecolor($new_w,$new_h);

					imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));

					imagejpeg($dst_img, "$cfg_thumb_path"."/$entry", 100);
						
					imagedestroy($dst_img);

				} elseif  ($img_type=="3") {

					$src_img=ImageCreateFrompng($cfg_fullsizepics_path."/".$entry);
					 
					$dst_img=ImageCreateTrueColor($new_w,$new_h);
						
					ImageCopyResampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,ImageSX($src_img),ImageSY($src_img));

					Imagepng($dst_img, "$cfg_thumb_path"."/$entry",100);

					imagedestroy($dst_img);

				} elseif  ($img_type=="1") {

					$cfg_thumb_url=$cfg_fullsizepics_url;

				} 

			}



		} //the files are now in the /images/content/sketchup/thumbs directory

		$this->setRedirect( 'index.php?option=' . $option . '&task=thumbs', 'Thumbnails are made' );

	} // the end of thumbnail creation
	
	
	function makeSiteImages()
	{

		global $option, $mainframe;

		//First we'll nee access to the file system and we'll use the Joomla way to be all safe.
		jimport('joomla.filesystem.file');
		$uploads_path = JPATH_ROOT . DS . "images". DS ."content" . DS ."sketchup". DS . "uploads" ;
		$site_path = JPATH_ROOT . DS . "images". DS ."content" . DS ."sketchup". DS . "site" ;

		// this is the width in px that we're telling GD to scale to, where's imagemagik when you need it.
		$new_w = 235;
		// where our source images live b/c GD needs to read them
		$cfg_fullsizepics_path = $uploads_path;
		//where we're sending them when we are done
		$cfg_thumb_path = $site_path;
		// we need one more path for this to work
		$filepath = $uploads_path ;
		// the directory
		$dir = dir($filepath);

		//check folders
			
		while($entry=$dir->read()) {
			//check the files
			if($entry == "." || $entry == "..") {

				continue;
			}
				
			$fp = @fopen("$filepath/$entry","r");

			$photo_filename = "$entry";

			$image_stats = GetImageSize($cfg_fullsizepics_path."/".$entry);

			$imagewidth = $image_stats[0];

			$imageheight = $image_stats[1];

			$img_type = $image_stats[2];

			$ratio = ($imagewidth / $new_w);

			$new_h = round($imageheight / $ratio);

			if (!file_exists($cfg_thumb_path."/".$entry))  {

				if ($img_type=="2") {

					$src_img = imagecreatefromjpeg($cfg_fullsizepics_path."/".$entry);

					$dst_img = imagecreatetruecolor($new_w,$new_h);

					imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));

					imagejpeg($dst_img, "$cfg_thumb_path"."/$entry", 100);
						
					imagedestroy($dst_img);

				} elseif  ($img_type=="3") {

					$src_img=ImageCreateFrompng($cfg_fullsizepics_path."/".$entry);
					 
					$dst_img=ImageCreateTrueColor($new_w,$new_h);
						
					ImageCopyResampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,ImageSX($src_img),ImageSY($src_img));

					Imagepng($dst_img, "$cfg_thumb_path"."/$entry",100);

					imagedestroy($dst_img);

				} elseif  ($img_type=="1") {

					$cfg_thumb_url=$cfg_fullsizepics_url;

				} 

			}


				
		} //the files are now in the /images/content/sketchup/site directory


		$this->setRedirect( 'index.php?option=' . $option . '&task=thumbs', 'Site Images made' );
	} //the end of Site image creation

	
	function moveSiteImages(){
	
		global $option, $mainframe;

		//we'll need access to the file system and we'll use the Joomla way to be all safe.
		jimport('joomla.filesystem.file');
	
		// define where the images are and where we want to put them

		$searchpath = JPATH_ROOT . DS . "images". DS ."content" . DS ."sketchup". DS . "uploads" ;
		$destpath = JPATH_ROOT . DS . "images". DS ."content" . DS ."sketchup". DS . "tmp" ;

		//read all the image files and put them in an array.
		$img_files = JFolder::files($searchpath, '.*');

		//Now we need some stuff from the JFile:: class to move all files into the new folder
		foreach ($img_files as $file) {
			JFile::move($searchpath. DS . $file, $destpath . DS. $file);
		}

		$this->setRedirect( 'index.php?option=' . $option . '&task=thumbs', 'Images Moved' );
	
	}

} //this is the end of the controller
?>
